package com.fingard.dsp.bank.directbank.xwbank02;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.text.StringHelper;
import com.xwbank.sdk.XWBankPay;
import com.xwbank.sdk.entity.BindingCardConfirmationInfo;
import com.xwbank.sdk.entity.BindingResultQueryInfo;
import com.xwbank.sdk.entity.PretieCardInfo;

import java.util.Map;

public class XWBank02Contract extends XWBank02Base implements IContract {
	@Override
	public RetAtsContract contract(ReqContract p_req) throws Exception {
		RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
		RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
		tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;

		try {
			String propertiesPath = getBankConfig().getValueAsString("propertiesPath");
			String merchantId = getBankConfig().getValueAsString("merchantId");
			String ownKeyStorePath = getBankConfig().getValueAsString("ownKeyStorePath");
			if (StringHelper.isNullOrEmpty(propertiesPath) || StringHelper.isNullOrEmpty(merchantId) || StringHelper.isNullOrEmpty(ownKeyStorePath)) {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "缺失'propertiesPath/merchantId/ownKeyStorePath'配置或节点内容为空!";
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			boolean initSuccess = XWBankPay.init(getConfigPath(propertiesPath), getConfigPath(ownKeyStorePath));
			if (!initSuccess) {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "config.properties配置有误!";
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			Map<String, Object> tmpMapRet = null;
			if ("01".equals(p_req.contractDetail.step)) {
				PretieCardInfo contractSubmit = new PretieCardInfo();
				
				contractSubmit.setVersion("1.0");
				contractSubmit.setMcht_no(merchantId);
				contractSubmit.setTran_no(p_req.contractDetail.askNumber);
				String cardType = "";
				if ("3".equals(p_req.contractDetail.cardType) || "4".equals(p_req.contractDetail.cardType)) {
					cardType = "CREDIT";// 信用卡
				} else {
					cardType = "DEBIT";// 借记卡
				}
				contractSubmit.setAcct_type(cardType);
				contractSubmit.setAcct_name(p_req.contractDetail.payName);
				contractSubmit.setCer_type("B01");
				contractSubmit.setCer_no(p_req.contractDetail.certNum);
				contractSubmit.setCvn(p_req.contractDetail.cvv2);
				contractSubmit.setValid_date(p_req.contractDetail.expiredDate);// 格式: MMYY
				contractSubmit.setAcct_no(p_req.contractDetail.payAct);
				contractSubmit.setPhone(p_req.contractDetail.cellPhone);
				contractSubmit.setSource_type("");
				contractSubmit.setConsumer_id("");
				
				writeBankLogStep2(contractSubmit);
				
				tmpMapRet = XWBankPay.getInstance().pretieCard(contractSubmit);
			} else if ("02".equals(p_req.contractDetail.step)) {
				BindingCardConfirmationInfo contractConfirm = new BindingCardConfirmationInfo();
				
				contractConfirm.setVersion("1.0");
				contractConfirm.setMcht_no(merchantId);
				contractConfirm.setTran_no(p_req.contractDetail.askNumber);
				contractConfirm.setChk_mesg(p_req.contractDetail.smsCode);
				contractConfirm.setUnique_code(p_req.contractDetail.token);
				contractConfirm.setSource_type("");
				contractConfirm.setConsumer_id("");
				
				writeBankLogStep2(contractConfirm);
				
				tmpMapRet = XWBankPay.getInstance().bindingCardConfirmation(contractConfirm);
			} else {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
				tmpRetDetail.signState = ContractState.FAIL;
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			writeBankLogStep3(tmpMapRet);
			
			if (tmpMapRet != null) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
				tmpRetDetail.respInfo = (String) tmpMapRet.get("returnMsg");
				
				String tmpRespCode = (String) tmpMapRet.get("returnCode");
				if ("000000".equals(tmpRespCode)) {
					JSONObject tmpJsonRet = JSONObject.parseObject((String) tmpMapRet.get("data"));
					
					String returnMsg = tmpJsonRet.getString("return_message");
					if (StringHelper.hasAnyChar(returnMsg)) {
						tmpRetDetail.respInfo = returnMsg;
					}
					
					String result = tmpJsonRet.getString("result");
					if ("01".equals(p_req.contractDetail.step)) {
						if ("0".equals(result)) {
							tmpRetDetail.token = tmpJsonRet.getString("unique_code");
						} else {
							tmpRetDetail.respCode = "-1";
						}
					} else {
						if ("0".equals(result)) {
							tmpRetDetail.signState = ContractState.SUCCESS;
						} else if ("1".equals(result)) {
							tmpRetDetail.signState = ContractState.FAIL;
						} else {
							tmpRetDetail.signState = ContractState.SIGNING;
						}
					}
					WriteBankLogLn2("签约信息映射码原始码:" + tmpJsonRet.getString("return_code"));
					tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpJsonRet.getString("return_code"));
				} else {
					// 网关错误也需要使用查询接口查回最终状态再判定支付状态
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = (String) tmpMapRet.get("returnMsg");
				}
				tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpRespCode);
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "银行返回内容为空!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }

    /**
	 * 签约查询
	 *     注意：同一个账号可能会多次绑卡，需要上送预绑卡流水号
	 *     原因：比如有存量直接迁移的签约数据，还有可能有异常没拿到签约结果的数据
	 */
	@Override
	public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
		RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
		RetAtsContractDetail tmpRetDetail = new RetAtsContractDetail();
		tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
		
		try {
			String propertiesPath = getBankConfig().getValueAsString("propertiesPath");
			String merchantId = getBankConfig().getValueAsString("merchantId");
			String ownKeyStorePath = getBankConfig().getValueAsString("ownKeyStorePath");
			if (StringHelper.isNullOrEmpty(propertiesPath) || StringHelper.isNullOrEmpty(merchantId) || StringHelper.isNullOrEmpty(ownKeyStorePath)) {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "缺失'propertiesPath/merchantId/ownKeyStorePath'配置或节点内容为空!";
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			boolean initSuccess = XWBankPay.init(getConfigPath(propertiesPath), getConfigPath(ownKeyStorePath));
			if (!initSuccess) {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "config.properties配置有误!";
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			BindingResultQueryInfo qryContract = new BindingResultQueryInfo();
			
			qryContract.setVersion("1.0");
			qryContract.setMcht_no(merchantId);
			qryContract.setTran_no("");
			qryContract.setSource_type("");
			qryContract.setConsumer_id("");
			qryContract.setAcct_no("");
			qryContract.setOrig_tran_no(p_reqQry.contractDetail.askNumber);
			
			writeBankLogStep2(qryContract);
			
			Map<String, Object> tmpMapRet = XWBankPay.getInstance().bindingResultQuery(qryContract);
			
			writeBankLogStep3(tmpMapRet);
			
			if (tmpMapRet != null) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.reqSeqID = p_reqQry.contractDetail.askNumber;
				tmpRetDetail.respInfo = (String) tmpMapRet.get("returnMsg");
				
				String tmpRespCode = (String) tmpMapRet.get("returnCode");
				if ("000000".equals(tmpRespCode)) {
					JSONObject tmpJsonRet = JSONObject.parseObject((String) tmpMapRet.get("data"));
					
					String returnMsg = tmpJsonRet.getString("return_message");
					if (StringHelper.hasAnyChar(returnMsg)) {
						tmpRetDetail.respInfo = returnMsg;
					}
					
					String result = tmpJsonRet.getString("orig_result");
					if ("0".equals(result)) {
						tmpRetDetail.signState = ContractState.SUCCESS;
					} else if ("1".equals(result)) {
						tmpRetDetail.signState = ContractState.FAIL;
					} else {
						tmpRetDetail.signState = ContractState.UNSIGNED;
					}
					
					if ("0".equals(result)) {
						tmpRetDetail.payAct = tmpJsonRet.getString("acct_no");
						tmpRetDetail.payName = tmpJsonRet.getString("acct_name");
						
						String cardType = tmpJsonRet.getString("acct_type");
						if ("CREDIT".equals(cardType)) {
							cardType = "3";
						} else {
							cardType = "2";
						}
						tmpRetDetail.cardType = cardType;
						tmpRetDetail.certType = "0";
						tmpRetDetail.certNum = tmpJsonRet.getString("cer_no");
						tmpRetDetail.cellPhone = tmpJsonRet.getString("phone");
					}
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = (String) tmpMapRet.get("returnMsg");
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "银行返回内容为空!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }
}
